///
/// 张诚宇
///
/// 推荐新闻首页
///
/// 2022.6.14
///
import 'package:chewie/chewie.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:video_player/video_player.dart';
import 'package:zhangchengyu20220614/cacheimage.dart';
import 'package:zhangchengyu20220614/model/NewsListEntity.dart';
import 'package:zhangchengyu20220614/model/VideoListEntity.dart' as Vl;
import 'package:zhangchengyu20220614/model/httputils.dart';
import 'package:zhangchengyu20220614/un_quick_tap.dart';
import 'package:zhangchengyu20220614/view/newsmessage.dart';

class NewsOneFragment extends StatefulWidget {
  const NewsOneFragment({Key key}) : super(key: key);

  @override
  _NewsOneFragmentState createState() => _NewsOneFragmentState();
}

class _NewsOneFragmentState extends State<NewsOneFragment> with AutomaticKeepAliveClientMixin{

  int _page=1;
  List<Result> _list=[];
  List<Vl.Result> _list2=[];
  RefreshController _controller;
  int num=1;
  var videoPlayerController;
  ChewieController chewieController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = RefreshController();
    NetWorkManaget().netWorkGet('http://mobile.bwstudent.com/hotNews/video/v1/findVideoList',map: {'columnId':1001,'page':1,'size':1},onSuccess: (data){
      setState(() {
        _list2.clear();
        _list2.addAll(Vl.VideoListEntity.fromJson(data).result);
        videoPlayerController = VideoPlayerController.network(_list2[0].videoUrl);
        chewieController=ChewieController(
            videoPlayerController: videoPlayerController,aspectRatio: 16/9,autoInitialize: true);
      });
    });
    getNewsList();

  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: _list.length<=0 || _controller == null? Center(child: CircularProgressIndicator(color: Colors.deepOrange,),) : SmartRefresher(
        controller: _controller,
        enablePullDown: true,
        enablePullUp: true,
        onRefresh: (){
          _page=1;
          getNewsList();
        },
        onLoading: (){
          _page++;
          getNewsList();
        },
        child: ListView.builder(itemBuilder: (context,index){
          if(_list[index].whetherAdvertising==1){

            if(_list[index].thumbnailUrl==null){
              return UnQuickTap(
                myTap: (){
                  Navigator.push(context, MaterialPageRoute(builder: (context)=>NewsMessagePage(newsId: _list[index].newsId,)));
                },
                child: Container(
                  margin: EdgeInsets.all(10),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(_list[index].title),
                      SizedBox(height: 10,),
                      Text(_list[index].authorName)
                    ],
                  ),
                ),
              );
            }else{
              var length = _list[index].thumbnailUrl.split(';').length;
              if(length==1){
                return UnQuickTap(
                  myTap: (){
                    Navigator.push(context, MaterialPageRoute(builder: (context)=>NewsMessagePage(newsId: _list[index].newsId,)));
                  },
                  child: Row(
                    children: [
                      Expanded(flex: 2,child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(_list[index].title),
                          SizedBox(height: 15,),
                          Text(_list[index].authorName),
                        ],
                      )),
                      Expanded(child: ClipRRect(borderRadius: BorderRadius.circular(5),child: cacheImage(_list[index].thumbnailUrl,width: 100,height: 100)),)
                    ],
                  ),
                );
              }else{
                return getMorePic(_list[index]);
              }
            }
          }else if(_list[index].whetherAdvertising==2){
            return Container(margin: EdgeInsets.all(10),child: cacheImage(_list[index].infoAdvertisingVo.adImageUrl,width: MediaQuery.of(context).size.width-15,height: 130));
          }else{
            return Column(
              children: [
                Text(_list[index].title),
                SizedBox(height: 5,),
                getVideo(_list[index]),
              ],
            );
          }
        },itemCount: _list.length,),
      ),
    );
  }

  void getNewsList() {
    NetWorkManaget().netWorkGet('http://mobile.bwstudent.com/hotNews/news/v1/findColumnNewsList',isCache: true,map: {'columnId':1001,'page':_page,'size':5},onSuccess: (data){
      _controller.loadComplete();
      _controller.refreshCompleted();
      if(_page==1){
        _list.clear();
      }
      if(NewsListEntity.fromJson(data).result.length<5){
        _controller.loadNoData();
      }else{
        _controller.resetNoData();
      }
      setState(() {

        _list.addAll(NewsListEntity.fromJson(data).result);
        if(_page==1 && chewieController!=null){
          // if(_list2.length!=0){
            _list.add(Result(authorImgUrl: _list2[0].videoUrl,title: _list2[0].title,whetherAdvertising: 3));
          // }
        }
      });
    });
  }

  Widget getMorePic(Result list) {

    List<Widget> _list=[];
    if(list.thumbnailUrl.endsWith(';')){
      _list.clear();
      var split = list.thumbnailUrl.split(';');
      split.removeAt(split.length-1);
      print(split.toString());
      for(int i=0;i<split.length;i++){
        print('${i}');
        _list.add(Expanded(child: ClipRRect(child: cacheImage(split[i]),borderRadius: BorderRadius.circular(5),)));
      }
      return UnQuickTap(
        myTap: (){
          Navigator.push(context, MaterialPageRoute(builder: (context)=>NewsMessagePage(newsId: list.newsId,)));
        },
        child: Container(
          margin: EdgeInsets.all(10),
          child: Column(
            children: [
              Text(list.title),
              SizedBox(height: 10,),
              Row(
                children: _list,
              ),
              SizedBox(height: 8,),
              Text(list.authorName),
            ],
          ),
        ),
      );

    }



  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  getVideo(Result list) {

    return AspectRatio(aspectRatio: chewieController.aspectRatio,child: Chewie(controller: chewieController,),);
  }


}
